<template>
  <div class="dashboard-container">
    <div class="filter-container">
      <el-row :gutter="10" style="width:100%;margin-bottom:10px">
        <el-col :span="3">
          <el-input
            v-model="listQuery.trade_code"
            placeholder="系统编号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.merge_code"
            placeholder="合并提单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.code"
            placeholder="真实提单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="listQuery.ship_start"
            style="width: 100%;"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="发船开始日期"
            end-placeholder="发船结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="listQuery.created"
            style="width: 100%;"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="创建开始日期"
            end-placeholder="创建结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>

        <el-col :span="6">
          <div style="display:flex">
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="reloadList"
            >搜索</el-button>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              icon="el-icon-edit"
              type="primary"
              @click="addNews"
            >
              添加
            </el-button>
            <download-excel
              style="margin-left:10px"
              class="export-excel-wrapper"
              :fetch="importPackageList"
              :fields="json_fields"
              type="xls"
              worksheet="My Worksheet"
              name="提单列表"
              :before-generate="startDownload"
              :before-finish="finishDownload"
            >
              <el-button type="primary">导 出</el-button>
            </download-excel>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              icon="el-icon-folder"
              type="primary"
              @click="merge()"
            >
              合并提单号
            </el-button>

          </div>
        </el-col>
      </el-row>

    </div>
    <div style="padding:0 20px">

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        height="calc(100vh - 250px)"
        style="width: 100%;"
        size="mini"
        border
        tooltip-effect="dark"
        :header-cell-style="{ background: '#eaf1fd', color: '#333' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="40"
        />
        <el-table-column
          label="系统编号"
          width="200px"
          prop="trade_code"
        />
        <el-table-column
          label="真实提单号"
          width="150px"
          prop="code"
        />
        <el-table-column
          label="合并提单号"
          width="150px"
          prop="merge_code"
        />
        <el-table-column
          label="航班号"
          width="150px"
          prop="flight.flight_number"
        />
        <el-table-column
          label="状态"
          width="100px"
        >
          <template slot-scope="{ row }">
            <div>
              <span v-if="row.status == 1" style="color:blue">进行中</span>
              <span v-if="row.status == 0" style="color:red">待进行</span>
              <span v-if="row.status == 2">已完成</span>
            </div>
          </template>

        </el-table-column>

        <el-table-column
          label="扫面件数"
          prop="scan_num"
          width="100px"
        />
        <el-table-column
          label="扫描重量(kg)"
          prop="scan_weight"
          width="100px"
        />
        <el-table-column
          label="使用日期"
          prop="use_date"
          width="140px"
        />

        <el-table-column
          label="发船时间"
          prop="ship_start"
          width="140px"
        />
        <el-table-column
          label="创建人"
          prop="admin.username"
          width="140px"
        />
        <el-table-column
          label="创建时间"
          prop="created"
          width="140px"
        />
        <!-- <el-table-column
          label="更新时间"
          prop="update_time"
          width="140px"
        /> -->
        <el-table-column
          label="操作"
          align="right"
          width="220"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              size="mini"
              type="primary"
              @click="edit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="printOpen(row)"
            >
              打印
            </el-button>
            <el-button
              type="danger"
              @click="delet(row)"
            >
              废弃
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <Detial :list-courier="listCourier" :country-code-list="countryCodeList" :port-list="portList" :detial="detial" :status="status" :visible="visible" @update="closeDraw" @reload="reloadList" />

    <el-dialog
      title="打印设置"
      :visible.sync="dialogPrint"
      width="400px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        <div style="margin-bottom:10px">
          <span style="display:inline-block;width:60px;text-align:right;margin-right:10px">提单号:</span>
          <el-input v-model="trade_code" style="width: 250px;" disabled />
        </div>
        <div style="margin-bottom:10px">
          <span style="display:inline-block;width:60px;text-align:right;margin-right:10px">打印机:</span>
          <el-select v-model="printerName" placeholder="请选择打印机" size="mini" style="width: 250px;">
            <el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </div>
        <div>
          <span style="display:inline-block;width:60px;text-align:right;margin-right:10px">快递公司:</span>
          <el-select v-model="printerCompany" placeholder="请选择快递公司" size="mini" style="width: 250px" @change="getprintList">
            <el-option v-for="item in listCourier" :key="item.company_code" :label="item.company_name" :value="item.company_code" />
          </el-select>
        </div>
        <div style="margin-top:20px">
          共需打印 <span style="color:red">{{ printInfo.total }}</span> 条数据
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPrint = false">取 消</el-button>
        <el-button type="primary" @click="submitPrint()">开始打印</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="合并提单"
      :visible.sync="dialogMerge"
      width="400px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        <el-input
          v-model="merge_code"
          placeholder="请输入合并号码"
          clearable
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMerge = false">取 消</el-button>
        <el-button type="primary" @click="submitMerge()">合并</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listCustomsAffairs, delCustomsAffairs, listWaybillNo, createMergeCode } from '@/api/lading/index'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Detial from './components/ladDetial.vue'
import { listPort } from '@/api/base/port'
import { countryCode } from '@/api/base/lines'
import { listCourierNo } from '@/api/base/express'
import { doConnect, doPrintHandover } from '@/utils/print'
import { expressLabel, printTimes } from '@/api/order/index'
import _ from 'lodash'

export default {
  name: 'Dashboard',
  components: {
    Pagination,
    Detial
  },
  data() {
    return {
      dialogMerge: false,
      merge_code: '',
      data_arr: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        trade_code: '',
        code: '',
        merge_code: '',
        ship_start: [],
        created: []
      },
      visible: false,
      status: 1,
      id: '',
      detial: {},
      portList: [],
      countryCodeList: [],
      listCourier: [],

      printerList: [],
      printLoading: null,
      back: {},
      dialogPrinters: false,
      printerName: '', // 选择的打印机名称
      printerCompany: 'SF-QD',
      dialogPrint: false,
      trade_code: '',
      printInfo: {},
      selectList: [],
      json_fields: {
        系统编号: {
          field: 'trade_code',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        真实提单号: {
          field: 'code',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        合并提单号: {
          field: 'merge_code',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        航班号: 'flight.flight_number',
        新额度: 'credit_amount_end',
        状态: {
          field: 'status',
          // 自定义回调函数
          callback: value => {
            if (value === 1) return '进行中'
            if (value === 0) return '待进行'
            if (value === 2) return '已完成'
          }
        },
        扫面件数: 'scan_num',
        '扫描重量(kg)': 'scan_weight',
        使用日期: 'use_date',
        发船时间: 'ship_start',
        创建人: 'admin.username',
        创建时间: 'created'
      }
    }
  },
  computed: {
  },
  watch: {
    back(val) {
      // 打印回调
      printTimes({ tid: val.printStatus[0].documentID }).then(res => {

      })
      this.printLoading.close()
    }
  },
  mounted() {
    var that = this
    const socket = doConnect()
    socket.onmessage = function(event) {
      console.log(JSON.parse(event.data))
      const res = JSON.parse(event.data)
      if (res.cmd === 'getPrinters') {
        that.printerName = res.defaultPrinter // 默认打印机
        that.printerList = res.printers
      }
      if (res.cmd === 'print') {
        that.printLoading = that.$loading({
          lock: true,
          text: '打印中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      if (res.cmd === 'notifyPrintResult' && res.taskStatus === 'printed') {
        that.back = res
      }
    }
  },
  created() {
    this.getList()
    this.getPort()
    this.getCountryCode()
    this.getCompanyList()
  },
  methods: {
    submitMerge() {
      const trade_code = this.selectList.map(item => {
        return item.trade_code
      })
      createMergeCode({
        'trade_codes': trade_code,
        'merge_code': this.merge_code
      }).then(res => {
        this.$message({
          type: 'success',
          message: '合并成功!'
        })
        this.dialogMerge = false
        this.getList()
      })
    },
    merge() {
      if (!this.selectList.length) {
        this.$message.error('请选择要合并的提单')
        return
      }
      this.merge_code = ''
      this.dialogMerge = true
    },
    handleSelectionChange(val) {
      this.selectList = val
    },
    handleClose() {
      this.dialogPrint = false
      this.dialogMerge = false
    },
    printOpen(row) {
      this.dialogPrint = true
      this.trade_code = row.trade_code
      this.getprintList()
    },
    getprintList() {
      listWaybillNo({
        'trade_code': this.trade_code,
        'company_code': this.printerCompany
      }).then(res => {
        this.printInfo = res.data
      })
    },
    print(waybill_no) {
      return new Promise((resolve, reject) => {
        expressLabel({
          waybill_no: waybill_no
        }).then(res => {
          resolve(res.data)
        })
      })
    },
    // 开始打印
    async submitPrint() {
      if (!this.printInfo.list.length) return this.$message.error('无打印数据')
      for (let index = 0; index < this.printInfo.list.length; index++) {
        const element = this.printInfo.list[index]
        const data = await this.print(element)
        const arr = []
        arr.push(data)
        doPrintHandover(arr, this.printerName)
      }
    },
    // 口岸列表
    getPort() {
      listPort({
        limit: 1000,
        status: 1
      }).then(response => {
        this.portList = response.data.data
      })
    },
    // 发出国列表
    getCountryCode() {
      countryCode({}).then(res => {
        this.countryCodeList = res.data
      })
    },
    // 快递公司列表
    getCompanyList() {
      listCourierNo({}).then(res => {
        this.listCourier = res.data
      })
    },
    closeDraw() {
      this.visible = false
    },
    addNews() {
      this.status = 1
      this.visible = true
    },
    edit(row) {
      this.detial = { ...row }
      this.status = 2
      this.visible = true
    },
    delet(row) {
      this.$confirm('确认废弃该提单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCustomsAffairs({
          id: row.id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '废弃成功!'
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    reloadList() {
      this.listQuery.page = 1
      this.visible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      listCustomsAffairs(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // 导出
    getPageSize() {
      return new Promise((resolve, reject) => {
        listCustomsAffairs(this.listQuery).then(response => {
          resolve(response.data.total)
        })
      })
    },
    getExcelList(page) {
      const param = _.cloneDeep(this.listQuery)
      param.page = page
      return new Promise((resolve, reject) => {
        listCustomsAffairs(param).then(response => {
          // response.data.list.forEach(item => {
          //   item.mobile = '+' + _.get(item.user, 'area_code', '') + ' ' + _.get(item.user, 'mobile', '')
          // })
          resolve(response.data.data)
        })
      })
    },
    async importPackageList() {
      const total = await this.getPageSize()
      const page = Math.ceil(total / this.listQuery.limit)
      var data = []
      for (let i = 1; i <= page; ++i) {
        data = data.concat(await this.getExcelList(i))
      }
      return data
    },
    startDownload() {
      this.loadingExcel = this.$loading({
        lock: true,
        text: '导出表格中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    finishDownload() {
      this.loadingExcel.close()
    }
  }
}
</script>
<style scoped>
.filter-container{
  padding:20px 20px 10px;
}

.upload-demo{
  margin: 20px 0 10px;
}
</style>
